<template>
  <div>
    <h5 class="text-muted">当前任务：放款登记</h5>
    <el-form class="query-table-form" @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <select-address
          v-model="params.address_code"
          :auto-top="true"
          @change="getData"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="企业名称查询"
          :clearable="true"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.lender_idcard"
          placeholder="身份证号码查询"
          :clearable="true"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.corp_name"
          placeholder="经营者名称查询"
          :clearable="true"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox
          v-model="params.has_ele_fee"
          border
          :true-label="1"
          false-label=""
          @change="getData"
        >
          电表
        </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
    </el-form>

    <c-table border class="table-sm" v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:address="scope">
        <div class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</div>
      </template>

      <template v-slot:townStatus="scope">
        <span class="badge" :class="`badge-${scope.row.townStatusLabel.css}`">
          {{ scope.row.townStatusLabel.label }}
        </span>
      </template>

      <template v-slot:bankStatus="scope">
        <span class="badge" :class="`badge-${scope.row.bankStatusLabel.css}`">
          {{ scope.row.bankStatusLabel.label }}
        </span>
      </template>
      <template v-slot:letterStatus="scope">
        <span class="badge" :class="`badge-${scope.row.letterStatusStyle}`">
          {{ scope.row.letterStatusLabel }}
        </span>
      </template>

      <template v-slot:noticeStatus="scope">
        <span class="badge" :class="`badge-${scope.row.noticeStatusStyle}`">
          {{ scope.row.noticeStatusLabel }}
        </span>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <register-edit-contract-dialog
      :visible.sync="editContractVisible"
      :related-data="editContractRow"
      @success="handleFileSuccess('editContractRow')"
    ></register-edit-contract-dialog>
    <register-edit-notice-dialog
      :visible.sync="editNoticeVisible"
      :related-data="editNoticeRow"
      @success="handleFileSuccess('editNoticeRow')"
    ></register-edit-notice-dialog>
    <register-edit-reply-dialog
      :visible.sync="editReplyVisible"
      :related-data="editReplyRow"
      @success="handleFileSuccess('editReplyRow')"
    ></register-edit-reply-dialog>

    <register-view-contract-dialog
      :visible.sync="viewContractVisible"
      :related-data="viewContractRow"
    ></register-view-contract-dialog>
    <register-view-notice-dialog
      :visible.sync="viewNoticeVisible"
      :related-data="viewNoticeRow"
    ></register-view-notice-dialog>
    <register-view-reply-dialog
      :visible.sync="viewReplyVisible"
      :related-data="viewReplyRow"
    ></register-view-reply-dialog>

    <attach-cmpt :visible.sync="attachVisible" :customer-related-id="attachRelatedId"></attach-cmpt>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'

import RegisterEditContractDialog from '@/credit/views/county/mission/RegisterEditContractDialog'
import RegisterEditNoticeDialog from '@/credit/views/county/mission/RegisterEditNoticeDialog'
import RegisterEditReplyDialog from '@/credit/views/county/mission/RegisterEditReplyDialog'
import RegisterViewContractDialog from '@/credit/views/county/mission/RegisterViewContractDialog'
import RegisterViewNoticeDialog from '@/credit/views/county/mission/RegisterViewNoticeDialog'
import RegisterViewReplyDialog from '@/credit/views/county/mission/RegisterViewReplyDialog'

import AttachCmpt from '@/credit/views/city/program/Attach'
import SelectAddress from '@/components/select/SelectAddress'

import { enumOrgClass, enumMainType } from '@/credit/plugins/enum'
import {
  enumCreditLetterStatus,
  enumApprovalStatus,
  enumNoticeStatus,
} from '@/credit/plugins/enumTown'

const enumStatusStyle = {
  0: 'info',
  1: 'warning',
  2: 'success',
  3: 'danger',
}

// const enumRegisterStatus = {
//   0: '未放款',
//   1: '合同已处理',
//   2: '已发放款通知书',
//   3: '已登记还款列表'
// }

export default {
  components: {
    SelectAddress,
    RegisterEditContractDialog,
    RegisterEditNoticeDialog,
    RegisterEditReplyDialog,
    RegisterViewContractDialog,
    RegisterViewNoticeDialog,
    RegisterViewReplyDialog,
    AttachCmpt,
  },
  props: {},
  data() {
    return {
      params: {
        index: 1,
        size: 10,
        lender_idcard: '',
        customer_name: '',
        corp_name: '',
        // 'public_status.eq': 2,
        'submit_type.in': '1,2',
        // 'ele_letter_status.eq': 2,
        'service_id.eq': '',
      },
      loading: false,
      attachVisible: false,
      attachRelatedId: '',
      tableName: 'customer_related',
      tableData: [],
      totalCount: 0,
      tableColumns: [
        {
          attrs: { label: '主体名称', prop: 'customer_name', minWidth: '120px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '地址', prop: 'address' }, slot: 'address' },
        {
          attrs: { label: '组织形式', prop: 'org_class', align: 'center' },
          process: v => enumOrgClass[v] || '-',
        },
        { attrs: { label: '经营者姓名', prop: 'corp_name', align: 'center' } },
        { attrs: { label: '联系电话', prop: 'mobile_no', align: 'center' } },
        { attrs: { label: '放款金额', prop: 'reply_funds', align: 'center' } },
        { attrs: { label: '贷款年限', prop: 'load_years', align: 'center' } },
        {
          attrs: { label: '到期时间', prop: 'load_end_date', align: 'center' },
          process: v => (v && v.substr(0, 10)) || '-',
        },
        {
          attrs: { label: '是否联保', prop: 'gua_type', align: 'center' },
          process: v => enumMainType[v],
        },
        { attrs: { label: '委托合同', align: 'center' }, slot: 'bankStatus' },
        { attrs: { label: '担保合同', align: 'center' }, slot: 'townStatus' },
        { attrs: { label: '联保函状态', align: 'center' }, slot: 'letterStatus' },
        { attrs: { label: '放款通知书状态', align: 'center' }, slot: 'noticeStatus' },
        {
          attrs: { label: '操作', align: 'center', minWidth: 120 },
          operations: [
            {
              content: row => `编辑${row.buttonText}`,
              icon: 'fa fa-edit',
              event: this.handleEdit,
              ifRender: row => row.editVisible,
            },
            {
              content: row => `查看${row.buttonText}`,
              icon: 'fa fa-search',
              event: this.handleView,
              ifRender: row => row.viewVisible,
            },
            {
              content: '附件',
              icon: 'fa fa-file-image-o',
              event: this.hanleAttach,
            },
          ],
        },
      ],

      // 显示类型
      // 两种：
      // 1、没有条件查询所有登记项目时，要根据项目自身状态（合同处理、放款通知书、放款登记状态）来显示
      // 2、指定查询时（合同未处理、合同已处理、放款通知、放款登记），要人为指定显示哪一种
      //
      // -1: 全部 0: 合同未处理 1: 合同已处理 2: 放款通知 3: 放款登记
      showType: -1,

      // 登记
      editContractVisible: false,
      editContractRow: {},
      editNoticeVisible: false,
      editNoticeRow: {},
      editReplyVisible: false,
      editReplyRow: {},

      // 查看
      viewContractVisible: false,
      viewContractRow: {},
      viewNoticeVisible: false,
      viewNoticeRow: {},
      viewReplyVisible: false,
      viewReplyRow: {},
    }
  },
  computed: {
    ...mapGetters(['user', 'userId', 'clientId', 'job']),
    isManager() {
      return ['org_credit_super', 'org_c_manage', 'org_r_emp', 'org_r_manage', 'org_corp'].includes(
        this.job
      )
    },
    isUserTown() {
      return this.user.orgRegionLever === 3
    },
  },
  watch: {
    $route(route) {
      if (route.name === 'missionRegister') {
        this.getData()
      }
    },
  },
  created() {
    if (this.isUserTown) {
      this.params['service_id.eq'] = this.clientId
    } else {
      this.params['recommend_service.eq'] = this.clientId
      this.params['gua_type.eq'] = 1
    }
    this.getData()
  },
  mounted() {},
  methods: {
    hanleAttach(row) {
      this.attachVisible = true
      this.attachRelatedId = row.customer_related_id
    },
    async getData() {
      const params = { ...this.params }
      const status = this.$route.query.status
      this.showType = -1

      if (status !== undefined) {
        this.showType = +status
        switch (this.showType) {
          case 0:
            params['orWhere.ensure_status.eq'] = 0
            params['orWhere.gua_status.eq'] = 0
            break
          case 1:
            params['ensure_status.gt'] = 0
            break
          case 2:
            params['ensure_status.gt'] = 0
            break
          case 3:
            params['loan_notice_status.gt'] = 1
            break
        }
      }

      if (!this.isManager) {
        params['orWhere.res_a.eq'] = this.userId
        params['orWhere.res_b.eq'] = this.userId
      }

      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, {
          N1bank_lender_status: 'asc',
          N2approval_register_status: 'asc',
        })
      )
      this.loading = false

      const data = (res && res.data) || {}
      this.totalCount = data.totalCount
      this.tableData = (data.data || []).map(this.dataAdapter)
    },
    dataAdapter(item) {
      item.ensure_status = +item.ensure_status
      item.loan_notice_status = +item.loan_notice_status
      item.approval_register_status = +item.approval_register_status

      item.townStatusLabel = enumApprovalStatus[item.gua_status] || {}
      item.bankStatusLabel = enumApprovalStatus[item.ensure_status] || {}

      item.letterStatusLabel = enumCreditLetterStatus[item.gua_letter_status] || '-'
      item.letterStatusStyle = enumStatusStyle[item.gua_letter_status] || ''

      const noticeStatus = enumNoticeStatus[item.loan_notice_status] || {}
      item.noticeStatusLabel = noticeStatus.label || ''
      item.noticeStatusStyle = noticeStatus.css || ''

      item.editType = this.getShowTypeText(item)
      item.editVisible = this.getEditButtonVisible(item)
      item.viewVisible = this.getViewButtonVisible(item)
      item.buttonText = this.getButtonText(item)

      return item
    },
    handleFileSuccess(rowKey) {
      this.$store.dispatch('getTaskCountTown')
      this.getData().then(() => {
        this.refreshEditRow(rowKey)
      })
    },
    refreshEditRow(rowKey) {
      const { customer_related_id: id } = this[rowKey] || {}
      if (id) {
        const item = this.tableData.find(item => item.customer_related_id === id)
        this.$set(this, rowKey, item ? this.dataAdapter(item) : {})
      }
    },
    handleEdit(row) {
      this.$set(this, `edit${row.editType}Row`, { ...row })
      this.$set(this, `edit${row.editType}Visible`, true)
    },
    handleView(row) {
      this.$set(this, `view${row.editType}Row`, { ...row })
      this.$set(this, `view${row.editType}Visible`, true)
    },
    getShowTypeText(row) {
      switch (this.showType) {
        case -1:
          // approval_register_status 审批登记状态 0 未放款 1 合同已处理 2 已发放款通知书 3 已登记还款列表
          // loan_notice_status 放款通知状态(0 待通知 1 已通知 2 已回执)
          // ensure_status 委托合同状态(0 待设置 1 已设置 )
          if (row.approval_register_status === 1 || row.loan_notice_status >= 2) return 'Reply'
          if (row.loan_notice_status > 0 || row.ensure_status > 0) return 'Notice'
          return 'Contract'
        case 0:
          return 'Contract'
        case 1:
          return 'Contract'
        case 2:
          return 'Notice'
        case 3:
          return 'Reply'
      }
    },
    getViewButtonVisible(row) {
      switch (row.editType) {
        case 'Reply':
          return row.approval_register_status >= 1
        case 'Notice':
          return row.loan_notice_status > 0
        case 'Contract':
          return row.ensure_status > 0
      }
    },
    getEditButtonVisible(row) {
      switch (row.editType) {
        case 'Reply':
          return row.loan_notice_status < 3
        case 'Notice':
          return row.loan_notice_status < 2
        case 'Contract':
          return true
      }
    },
    getButtonText(row) {
      switch (row.editType) {
        case 'Reply':
          return '放款登记'
        case 'Notice':
          return '放款通知书'
        case 'Contract':
          return '合同'
      }
    },
  },
}
</script>
<style lang="scss" scoped></style>
